package com.xcc.netty.socket.bio;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author frosty
 * @description
 * @date 2019-12-30 30:14:13
 */


public class NioServer {

    public static void main(String[] args) throws  Exception{
         //线程池机制
          //创建一个线程   有链接创建一个线程
        ExecutorService threadPool= Executors.newCachedThreadPool();
        ServerSocket socket=new ServerSocket(8761);
        System.out.println("server start up");

        while (true){
             final Socket accept = socket.accept();
            System.out.println("link a client");
              threadPool.execute(new Runnable() {
                  @Override
                  public void run() {
                      handler(accept);
                  }
              });


        }


    }

     public static   void handler(Socket socket){
         try {
             byte[] buff=new byte[1024];
             int len=0;
               //这会阻塞
              InputStream is = socket.getInputStream();
              while ((len=is.read(buff))!=-1){
                  System.out.println("thread id is "+Thread.currentThread().getId());
                  System.out.println(new String(buff,0,len,"gbk"));
              }

         }catch (Exception e){
             e.printStackTrace();
         }finally {
             try {
                 socket.close();

             }catch (Exception e){
                 e.printStackTrace();
             }
         }


     }

}
